package com.zj.osm.utils

import android.util.Log
import com.zj.osm.entity.greendao.PowerSupplyScheme
import com.zj.osm.entity.greendao.PowerSupplySchemeDetails
import com.zj.utils.view.CustomXWPFDocument
import org.apache.poi.xwpf.usermodel.XWPFDocument
import org.apache.poi.xwpf.usermodel.XWPFFooter
import org.apache.poi.xwpf.usermodel.XWPFParagraph
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.InputStream

/**
 * 导出Word（供电方案）工具类
 *
 * @author jiang zhu on 2019/10/30
 */
class WordUtils {

    /**
     * 写入docx
     *
     * @param is                           模板
     * @param newFile                      新文件
     * @param map                          替换文件
     * @param powerSupplySchemes           基本信息
     * @param powerSupplySchemeDetailsList 电源信息
     */
    fun writeDoc(`is`: InputStream, newFile: File, map: HashMap<String, Any>, powerSupplySchemes: PowerSupplyScheme, powerSupplySchemeDetailsList: List<PowerSupplySchemeDetails>) {
        try {
            //自定义的XWPFDocument，解决官方版图片不显示问题
            val document = CustomXWPFDocument(`is`)
            //读取段落（一般段落，页眉页脚没办法读取）
            val listParagraphs = document.paragraphs
            processParagraphs(listParagraphs, map)

            //读取页脚
            val footerList = document.footerList
            processParagraph(footerList, map)

            //处理表格
            val it = document.tablesIterator
            while (it.hasNext()) {//循环操作表格
                val table = it.next()


                if (powerSupplySchemeDetailsList.size > 1) {
                    for (i in 3 + powerSupplySchemeDetailsList.size..10) {
                        val iss = 3 + powerSupplySchemeDetailsList.size
                        table.removeRow(iss)
                    }
                } else {
                    for (i in 5..10) {
                        table.removeRow(5)
                    }
                }

                val rows = table.rows
                for (row in rows) {//取得表格的行
                    val cells = row.tableCells
                    for (cell in cells) {//取得单元格

                        if ("\$IMG$" == cell.text) {
                            //直接插入图片会在文档的最底端，所以要插在固定位置，要把图片放在表格里
                            //所以使用判断单元格，并清除单元格放置图片的方式来实现图片定位
                            if (powerSupplySchemes.diagram != "") {
                                cell.removeParagraph(0)
                                val pargraph = cell.addParagraph()
                                document.addPictureData(FileInputStream(powerSupplySchemes.diagram), XWPFDocument.PICTURE_TYPE_PNG)
                                document.createPicture(document.allPictures.size - 1, 160, 280, pargraph)
                            }
                        }

                        val paragraphListTable = cell.paragraphs
                        processParagraphs(paragraphListTable, map)
                    }
                }
            }
            val fopts = FileOutputStream(newFile)
            document.write(fopts)
            fopts.close()
        } catch (e: Exception) {
            Log.e("TAG", "报错了: " + e.message)
            e.printStackTrace()
        }

    }

    //处理段落
    private fun processParagraphs(paragraphList: List<XWPFParagraph>?, param: Map<String, Any>) {
        if (paragraphList != null && paragraphList.isNotEmpty()) {
            for (paragraph in paragraphList) {
                val runs = paragraph.runs
                for (run in runs) {
                    var text: String? = run.getText(0)
                    if (text != null) {
                        var isSetText = false
                        for ((key, value) in param) {
//Log.e("TAG", "processParagraphs: " + text);
                            if (text!!.contains(key)) {
                                isSetText = true
                                if (value is String) {//文本替换
                                    text = text.replace(key, value.toString())
                                }
                            }
                        }
                        if (isSetText) {
                            run.setText(text, 0)
                        }
                    }
                }
            }
        }
    }


    //处理页脚中的段落，其实就是用方法读取了下页脚中的内容，然后也会当做一般段落处理
    private fun processParagraph(footerList: List<XWPFFooter>?, map: Map<String, Any>) {
        if (footerList != null && footerList.isNotEmpty()) {
            for (footer in footerList) {
                //读取一般段落
                val paragraphs = footer.paragraphs
                processParagraphs(paragraphs, map)
                //处理表格
                val tables = footer.tables
                for (i in tables.indices) {
                    val xwpfTable = tables[i]
                    val rows = xwpfTable.rows
                    for (row in rows) {//取得表格的行
                        val cells = row.tableCells
                        for (cell in cells) {//取得单元格
                            val paragraphListTable = cell.paragraphs
                            processParagraphs(paragraphListTable, map)
                        }
                    }
                }
            }
        }
    }



}